package bTree.LeetCode;

import java.util.*;

public class 克隆图 {
    public Node cloneGraph(Node node) {
        if (node == null) {
            return node;
        }
        HashMap<Node, Node> hashMap = new HashMap<>();
        Queue<Node> queue = new LinkedList<>();
        Node head = new Node(node.val);
        hashMap.put(node, head);
        queue.add(node);
        while (!queue.isEmpty()) {
            Node peek = queue.peek();
            List<Node> neighbors = peek.neighbors;
            Node node1 = hashMap.get(peek);
            for (Node neighbor : neighbors) {
                if (hashMap.containsKey(neighbor)) {
                    node1.neighbors.add(hashMap.get(neighbor));
                }else {
                    hashMap.put(neighbor, new Node(neighbor.val));
                    node1.neighbors.add(hashMap.get(neighbor));
                    queue.add(neighbor);
                }
            }
            queue.poll();
        }
        return head;
    }
}